<template>
  <div id="my_table" style="width: 100%">
    <div
      v-if="(fields === null || fields.length === 0) && loading == false"
      v-show="isShow"
      v-loading="loading"
      class="icon_tip"
      element-loading-text="奋力加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 1)"
    >
      <div class="center">
        <img src="../../assets/image/Frame 73.svg" alt class="image">
        <p class="c-333">数据为空</p>
        <p>暂时还没有内容呢...</p>
      </div>
    </div>
    <el-table
      v-else
      ref="checkTable"
      v-loading="loading"
      :header-cell-style="cellStyle"
      :data="records"
      :header-drag-style="true"
      size="small"
      :border="border"
      :row-class-name="tableRowClassName"
      :cell-style="unitCellStyle"
      :current-row-key="rowKey"
      :show-summary="summary"
      :row-key="getRowKeys"
      :summary-method="summaryMethod"
      :height="height"
      element-loading-text="奋力加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 1)"
      element-loading-color="#475ffd"
      :flag="flag"
      :is-click="isClick"
      :is-check="isCheck"
      :is-table="isTable"
      :highlight-current-row="false"
      @selection-change="handleSelectEvent"
      @cell-click="cellClick"
      @row-click="rowClick"
      @row-dblclick="rowDblclick"
      @select="clickSelect"
    >
      <template>
        <template v-if="loading == false&&records.length==0" slot="empty">
          <div class="center">
            <img src="../../assets/image/Frame 73.svg" alt class="image">
            <p class="c-333">数据为空</p>
            <p>暂时还没有内容呢...</p>
          </div>
        </template>
        <el-table-column
          v-if="isSelection && isCheck"
          :reserve-selection="true"
          :selectable="selectable"
          type="selection"
          width="55"
          align="center"
        />
        <el-table-column
          v-if="isSort"
          type="index"
          label="序号"
          width="60"
          align="center"
          :fixed="fixed"
        />

        <template v-for="(field, index) in fields">
          <el-table-column
            :key="index"
            resizable
            :prop="field.prop"
            :label="field.label"
            :fixed="field.fixed"
            :width="field.width"
            :render-header="questionIcon"
            :align="field.align ? field.align : 'center'"
            :show-overflow-tooltip="true"
          >
            <template v-if="field.children && field.children.length">
              <el-table-column
                v-for="(column, index1) in field.children"
                :key="index1"
                :prop="column.prop"
                :align="field.align ? field.align : 'center'"
                :width="field.colwidth"
                :label="column.label"
              />
            </template>
            <template slot-scope="scope">
              <span v-if="!$scopedSlots[field.prop]">
                {{
                  field.filter
                    ? field.filter(scope.row[field.prop])
                    : scope.row[field.prop]
                }}
              </span>
              <slot
                v-else
                :name="field.prop"
                :row="scope.row"
                :index="scope.$index"
              />
            </template>
          </el-table-column>
        </template>

        <el-table-column
          v-if="handle == true"
          label=""
          :align="'center'"
          :width="width"
        >
          <template slot="header">
            <i v-if="tools" class="el-icon-s-tools" @click="toolsOpen" /><span
              :class="tools ? 'handle' : ''"
            >操作</span></template>
          <template v-slot="{ row, column, rowIndex }">
            <slot
              name="operation"
              :row="row"
              :column="column"
              :$index="rowIndex"
            />
          </template>
        </el-table-column>
      </template>
    </el-table>
    <div v-if="isPaginationShow" class="pagination">
      <el-pagination
        ref="pagination"
        :current-page="paginationInfo.current"
        :page-sizes="paginationInfo.sizes"
        :page-size="paginationInfo.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </div>
  </div>
</template>
<script>
export default {
  name: 'HouseKeeperTable',
  components: {},
  props: {
    fixed: {
      type: Boolean,
      default: false
    },
    tools: {
      type: Boolean,
      default: false
    },
    isShow: {
      type: Boolean,
      default: true
    },
    width: {
      type: String,
      default: '55px'
    },
    // 是否把复选框禁用
    selectableBoo: {
      type: Boolean,
      default: false
    },
    isSort: {
      // 是否显示排序
      type: Boolean,
      default: true
    },
    isClick: {
      // 可否单击
      type: Boolean,
      default: true
    },
    isCheck: {
      // 可否多选
      type: Boolean,
      default: true
    },
    isTable: {
      // 是否至此禁用
      type: Boolean,
      default: false
    },
    // 单行颜色表格唯一标识，默认为id
    rowKey: {
      type: String,
      default: 'id'
    },
    border: {
      type: Boolean,
      default: true
    },
    // 是否自定义单元样式
    isCell: {
      type: Boolean,
      default: false
    },
    // 是否支持选中
    isSelection: {
      type: Boolean,
      default: false
    },
    // 是否开启操作栏
    handle: {
      type: Boolean,
      default: false
    },
    // 表头
    fields: {
      type: Array,
      default: () => []
    },

    tableHeadBackground: {
      type: String,
      default: '#D8D8D8'
    },
    tableHeadColor: {
      type: String,
      default: '#000'
    },
    height: {
      type: [Number, String]
    },
    cellStyle: {
      type: Object,
      // default: {}
      default: () => ({ backgroundColor: '#ffff' })
    },
    // 表格标识名称
    sessionName: {
      type: String
    },
    flag: {
      type: Boolean,
      default: false
    },
    // 是否开启合计
    summary: {
      type: Boolean,
      default: false
    },
    totalMoney: {
      type: Object,
      default: () => {
        return {}
      }
    },
    totalMoney1: {
      type: Object,
      default: () => {
        return {}
      }
    },
    isPaginationShow: {
      // 每一个调用table的组件需要传递一个参数，是否显示分页器
      type: Boolean,
      default: true
    },
    api: {
      type: String,
      default: null
    },
    values: {
      type: Object,
      default: {}
    }
  },

  data() {
    return {
      lastField: '',
      scrollEl: null,
      currentSelectedTime: null,
      multiSelected: [],
      multiSelectedId: [],
      time: null,
      selectArr: [],
      paginationInfo: {
        current: 1,
        size: 13,
        sizes: [10, 20, 30, 50]
      },
      total: 0,
      loading: true,
      records: [],
      model: {
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  computed: {},
  watch: {
    selectableBoo() {
      const that = this
      that.$nextTick(() => {
        setTimeout(() => {
          if (that.selectableBoo) {
            that.data.forEach((row) => {
              if (row.invoiceNo) {
                that.$refs.checkTable.toggleRowSelection(row, true)
              }
            })
          }
        }, 500)
      })
    }
  },
  created() {
    this.init()
  },
  mounted() {
    // 回显数据  DOMSubtreeModified
  },
  methods: {
    // 请求表格数据
    init() {
      const val = Object.assign(this.values, this.model)
      this.$tableApi[this.api](val).then(res => {
        this.records = res.list
        this.loading = false
        this.total = res.total
      }).catch(err => {
        this.loading = false
      })
    },
    toolsOpen() {
      this.$emit('toolsOpen')
    },
    // 页数
    currentChange(val) {
      this.model.pageNum = val
      this.init()
    },
    // 条数
    sizeChange(val) {
      this.model.pageSize = val
      this.$refs.pagination.internalCurrentPage = 1
      this.model.pageNum = 1
      this.init()
    },
    clickSelect(selection, row) {
    },

    questionIcon(h, { column, $index }) {
      if (column.label.length * 14 > 50) {
        return (
          <el-tooltip
            class='item'
            effect='dark'
            content={column.label}
            placement='top'
          >
            <span>{column.label}</span>
          </el-tooltip>
        )
      } else {
        return <span>{column.label}</span>
      }
    },
    getRowKeys(row) {
      return row.id
    },
    // 合计
    summaryMethod({ columns, data }) {
      const means = []
      const arr = []
      means.push('合计')
      if (this.isSelection) {
        means.push('')
      }
      this.fields.forEach((column, columnIndex) => {
        if (column.prop == 'myindex') {
          return
        }
        if (column.prop == 'id') {
          return
        }
        let boo = false
        if (this.totalMoney1) {
          for (const key in this.totalMoney1) {
            if (this.totalMoney1[key]) {
              if (column.prop == key) {
                means.push(this.totalMoney1[key].rentStatistical)
                means.push(this.totalMoney1[key].discountStatistical)
                means.push(this.totalMoney1[key].payStatistical)
                boo = true
                return
              }
            }
          }
        }
        if (this.totalMoney) {
          for (const key in this.totalMoney) {
            if (column.prop == key) {
              means.push(this.totalMoney[key] + '元')
              boo = true
              return
            }
          }
        }
        if (!boo) {
          means.push('')
        }
      })
      return means
    },
    // 重置表格
    reset(delList) {
      if (delList && delList.length > 0) {
        delList.map((item) => {
          sessionStorage.removeItem(item)
        })
      }
      this.$refs.checkTable.clearSelection()
    },

    deleteArr(arr) {
      let sessionArr = JSON.parse(
        sessionStorage.getItem(this.currentSessionName)
      )
      if (arr.length > 0) {
        const obj = arr[0]
        sessionArr = sessionArr.filter(
          (item) => item[this.rowKey] !== obj[this.rowKey]
        )
        sessionStorage.setItem(
          this.currentSessionName,
          JSON.stringify(sessionArr)
        )
        arr.splice(0, 1)
        this.deleteArr(arr)
      } else {
        if (sessionArr.length > 0) {
          sessionArr.map((item) => {
            const row = item
            this.$refs.checkTable.toggleRowSelection([
              { row: row, selected: true }
            ])
          })
        } else {
          this.$refs.checkTable.clearSelection()
        }
      }
    },
    // 删除选中列
    delFn(arr) {
      this.deleteArr(arr)
    },
    // 自定义单元样式
    unitCellStyle({ row, rowIndex, column }) {
      if (!this.isCell) return
    },
    // 选中时每行的颜色
    tableRowClassName({ row, rowIndex }) {
      for (const item in this.multiSelected) {
        if (this.multiSelected[item][this.rowKey] == row[this.rowKey]) {
          return 'current-row'
        }
      }
      if (rowIndex % 2 == 1) {
        // 奇数行
        return 'row-odd'
      } else {
        return 'row-even'
        // 偶数行
      }
    },
    // 当每行点击
    cellClick(row, column, event) {
      this.$emit('cellClick', row, column)
    },
    // 当每行双击
    rowDblclick(row, column) {
      this.$emit('rowDblclick', row, column)
    },

    handleSelectEvent(selection) {
      this.$emit('selectionFn', selection)
      this.multiSelected = selection
      this.multiSelectedId = this.multiSelected.map((item) => {
        return item[this.rowKey]
      })
    },
    // 决定这行的复选框是否可以勾选
    selectable(row, index) {
      const that = this
      if (that.selectableBoo) {
        return false
      } else {
        if (!that.flag) {
          return true
        }
        // if (row.payStatus === "已支付" || row.payStatus == 1) {
        //   return true;
        // } else {
        //   return false;
        // }
      }
    },
    // 点击当前行
    rowClick(row, column, cell, event) {
      const _this = this
      _this.$refs.checkTable.toggleRowSelection(row)
      _this.$emit('rowClick', row)
    }
  }
}
</script>

<style lang="scss">
.el-table th {
  background-color: #b2caec !important;
}
.el-table {
  height: 100%;
}
.el-table__row {
  height: 14px !important;
  color: rgba(0, 0, 0, 0.65);
  font-size: 15px;
  padding: 0;
}
.el-table th > .cell {
  color: #3a3a3d;
  font-size: 15px;
}
.pagination {
  width: 100%;
  background: #fff;
  margin-top: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
